﻿using System.Globalization;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using FanaticRock.Core.Models;
using FanaticRock.Extensions;

namespace FanaticRock.Converters
{
    public class ResourceSourceToImageBrushConverter : IValueConverter
    {
        #region instance 

        private ImageBrush _defaultImageBrush;

        public ResourceSourceToImageBrushConverter(ImageBrush defaultImageBrush)
        {
            _defaultImageBrush = defaultImageBrush;
        }

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {

            //return null;
            if (value is ResourceSource resourceSource)
            {
                var imageBrush = resourceSource.CreateImageBrush();
                if (imageBrush == null) return _defaultImageBrush;
                return imageBrush;
            }
            else
            {
                return null;
            }

            throw new NotImplementedException();
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion

        #region singleton

        private static Lazy<ResourceSourceToImageBrushConverter> _instance = new Lazy<ResourceSourceToImageBrushConverter>(CreateInstance);
        public static ResourceSourceToImageBrushConverter Instance => _instance.Value;

        private static ResourceSourceToImageBrushConverter CreateInstance()
        {
            var uri = new Uri(@"pack://application:,,,/FanaticRock.Resources;component/test.webp");
            var imageSource = new BitmapImage(uri);
            var imageBrush = new ImageBrush(imageSource) { Stretch = Stretch.UniformToFill };
            return new ResourceSourceToImageBrushConverter(imageBrush);
        }

        #endregion
    }
}
